package resources

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"strings"
)

type DownloadRequest struct {
	Path string `form:"path" validate:"required" binding:"required"` // 任务ID
	Name string `form:"name" validate:"required" binding:"required"` // 文件名称
}

func (cls *Resources) Download(c *gin.Context) {
	var body = DownloadRequest{}
	if err := c.ShouldBindQuery(&body); nil != err {
		c.AbortWithStatus(http.StatusBadRequest)

		return
	}

	path, err := cls.resources.AbsFilepath(strings.Split(body.Path, "/"), body.Name)
	if nil != err {
		c.AbortWithStatus(http.StatusNotFound)

		return
	}

	stat, err := os.Stat(path)
	if nil != err {
		c.AbortWithStatus(http.StatusNotFound)

		return
	}

	// 不能下载目录
	if stat.IsDir() {
		c.AbortWithStatus(http.StatusNotFound)

		return
	}

	c.FileAttachment(path, body.Name)
}
